package com.atstudent.gmall.rabbit.service.impl;/*
 * @author: XueYouPeng
 * @time: 23.9.19 上午 8:34
 */

import com.atstudent.gmall.rabbit.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.IOException;

@Service
@Slf4j
public class RabbitServiceImpl implements RabbitService {

    @Autowired
    private RedisTemplate<String , String > redisTemplate;

    //使用它是在OrderCloseListener  消费方使用的
    //重试机制

    @Override
    public void retry(Channel channel, long deliveryTag, String msgContent, int count) {

        //获取消息的实际消费次数
        String md5Msg = DigestUtils.md5DigestAsHex(msgContent.getBytes());
        Long msgCount = redisTemplate.opsForHash().increment("msg:count", md5Msg, count);
        //实际次数小于最大阈值 ，  返回nack
        if (msgCount < count){
            try {
                channel.basicNack(deliveryTag , true , true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {//实际消费次数大于最大阈值 ， 返回ack

            //  把消息写入到数据库中
            log.info("把消息写入到了数据库中，msg: {}" , msgContent);

            //返回ack
            try {
                channel.basicAck(deliveryTag , true);

                //删除掉Redis中消息的实际消费次数
                redisTemplate.opsForHash().delete("msg:count" , md5Msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
